import re
import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

def extractWords(dictPath):
    f = open(dictPath, encoding="UTF-8")
    strf = f.read() 
    # print("read")
    f.close()
    regex = r" \d+ \w+"
    pattern = re.compile(regex)
    strf = pattern.sub("", strf)
    return strf.split()

def setMaxlenOfCutWord(wordDict, maxLen):
    for i in wordDict:
        if len(i) > maxLen:
            wordDict.remove(i)

def BMM(inputString, maxlen, wordDict):
    cutWord = []
    curlenOfString = len(inputString)
    while curlenOfString > 0:
        curlenOfCut = maxlen
        while curlenOfCut > 0:
            if curlenOfString - curlenOfCut < 0:
                curlenOfCut -= 1
                continue
            if curlenOfCut == 1:
                cutWord.append(inputString[curlenOfString - 1])
                curlenOfString -= 1
                break
            tmpWord = inputString[curlenOfString - curlenOfCut : curlenOfString]
            if tmpWord in wordDict:
                cutWord.append(tmpWord)
                curlenOfString -= curlenOfCut
                break
            else:
                curlenOfCut -= 1
    cutWord.reverse()
    return cutWord

def FMM(inputString, maxlen, wordDict):
    cutWord = []
    curIndexOfString = 0
    length = len(inputString)
    while curIndexOfString < length:
        curlenOfCut = maxlen
        while curlenOfCut > 0:
            if curIndexOfString + curlenOfCut > length:
                curlenOfCut -= 1
                continue
            if curlenOfCut == 1:
                cutWord.append(inputString[curIndexOfString])
                curIndexOfString += 1
                break
            tmpWord = inputString[curIndexOfString : curIndexOfString + curlenOfCut]
            if tmpWord in wordDict:
                cutWord.append(tmpWord)
                curIndexOfString += curlenOfCut
                break
            else:
                curlenOfCut -= 1
    return cutWord

if __name__ == '__main__':
    inputString = "他是研究生物化学的"
    wordDict = extractWords("dict2.txt")
    #print(wordDict)
    maxLen = 4
    setMaxlenOfCutWord(wordDict, maxLen)
    cutWord = BMM(inputString, maxLen, wordDict)
    cutWord2 = FMM(inputString, maxLen, wordDict)
    print(cutWord)
    print(cutWord2)



